package com.artisan.domain.service;

import com.artisan.admin.resultModels.adResultModels.AdResultModel;
import com.artisan.domain.dto.AdDto;
import com.artisan.domain.dto.PageDto;
import com.artisan.domain.entity.MAd;
import com.artisan.domain.info.AdInfo;
import com.artisan.domain.repositoryInterface.IAdRepository;
import com.artisan.domain.serviceInterface.IAdService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 广告业务类
 */
@Service
public class AdService implements IAdService {

    private final IAdRepository blogRepository;

    public AdService(@Qualifier("IAdRepository") IAdRepository blogRepository) {
        this.blogRepository = blogRepository;
    }

    @Override
    public PageDto<AdDto> findList(String name, int pageIndex, int pageSize) {
        int index = pageIndex - 1;
        Pageable pageable = new QPageRequest(index, pageSize);
        Page<AdInfo> page = this.blogRepository.find(name, pageable);

        List<AdDto> dtos = new ArrayList<>();
        page.getContent().forEach(info -> {
            AdDto dto = new AdDto();
            dto.setId(info.getAd().getId());
            dto.setClickNum(info.getAd().getClickNum());
            dto.setName(info.getAd().getName());
            dto.setPhotoUrl(info.getAd().getPhotoUrl());
            dto.setAdPositionName(info.getAdPosition().getName());

            dtos.add(dto);
        });
        PageDto<AdDto> result = new PageDto();
        result.setContent(dtos);
        result.setNumber(page.getNumber());
        result.setSize(page.getSize());
        result.setTotalElements(page.getTotalElements());

        return result;
    }

    @Override
    public int add(AdDto dto) {
        MAd model = new MAd();
        model.setAdNo("0");
        model.setName(dto.getName());
        model.setAdPositionId(dto.getAdPositionId());
        model.setPhotoUrl(dto.getPhotoUrl());
        model.setClickNum(0);
        model.setAddDate(System.currentTimeMillis());
        model.setStatus(dto.getStatus());
        model.setRegion(dto.getRegion());
        model.setTypeId(dto.getTypeId());
        model.setLink(dto.getLink());
        model.setContent(dto.getContent());

        model = this.blogRepository.saveAndFlush(model);


        return model.getId();
    }
}
